<template>
  <div id="login">
    <div id="login_div">
      <h1>登录</h1>
      <el-form ref="loginForm" :model="loginData" :rules="loginRules">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-s-custom" v-model="loginData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-lock" type="password" v-model="loginData.password"></el-input>
        </el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
        <el-button type="primary" @click="register">注册</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() { // &#9989; 正确声明data
    return {
      // 表单数据对象
      loginData: {
        username: null,
        password: null,
      },
      // 验证规则
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在1到10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在1到10个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$http({
            url: "/user/login",
            method: "POST",
            data: this.loginData
          }).then(res => {
            if (res.data.code == 200) {
              this.$message({
                message: res.data.message,
                type: 'success'
              });
              // 保存token（示例）
              window.sessionStorage.setItem("token", res.data.token);
              // 跳转首页
              this.$router.push("/hello");
            } else {
              this.$message.error('登录失败');
            }
          });
        }
      });
    },
    register() { // &#9989; 补充注册方法
      this.$router.push("/register"); // 假设有注册页路由
    },
  }
};
</script>

<style scoped>
#login {
  height: 100%;
  background-image: url("../assets/login.jpg");
  background-repeat: no-repeat;
  background-size: cover; /* 优化背景显示 */
}
#login_div {
  width: 300px;
  position: absolute;
  top: 50%;
  left: 50%; /* 居中调整 */
  transform: translate(-50%, -50%);
  padding: 20px;
  background: rgba(255, 255, 255, 0.8); /* 增加半透明背景提升可读性 */
  border-radius: 5px;
}
</style>
